package org.nobject.common.lang;

import java.util.Arrays;

import org.nobject.common.exception.ConvertException;

/**
 * Char工具类
 *
 * @author bianrongjun
 * @version 1.0
 */
public class CharUtils {
	
	/**
	 * String转成char数组
	 * @param str 字符串
	 */
	public static char[] toChars(String str){
		char[] cs = new char[str.length()];
		str.getChars(0, str.length(), cs, 0);
		return cs;
	}
	
	/** 
	 * String转成char
	 * @param str 字符串
	 */
	public static char toChar(String str) throws ConvertException{
		if(str.length()>0) return str.charAt(0);
		throw new ConvertException("不支持空字符串到char的转换");
	}
	
	/** 
	 * 转成char
	 * @param obj 对象
	 */
	public static char toChar0(Object obj) throws ConvertException{
		if(obj==null) throw new ConvertException("char不支持Null转换");
		if (obj instanceof Character) return (Character)obj;
		Class clazz=obj.getClass();
		if(ClassUtils.isString(clazz)){
			return toChar((String)obj);
		}else if(ClassUtils.isByte(clazz)){
			return toChar(new String(new byte[]{(Byte)obj}));
		}else{
			throw new ConvertException("不支持"+clazz.getName()+"类型到Boolean的转换");
		}
	}
	
	
	/** 
	 * 是否为空白
	 * @param c 字符
	 */
	public static boolean isSpace(char c){
		if(c==' '||c=='\t'||c=='\n'||c=='\r'){
			return true;
		}
		return false;
	}
	
	/** 
	 * 移除起始重复的
	 * @param cs 原始
	 * @param c 被移除的字符
	 */
	public static char[] removeStartRepeat(char[] cs,char c){
		int l=cs.length;
		for(int i=0;i<l;i++){
			if(cs[i]!=c){
				return Arrays.copyOfRange(cs, i, l);
			}
		}
		return cs;
	}
	
	/** 
	 * 移除起始重复的
	 * @param cs 字符串
	 * @param c
	 */
	public static char[] removeEndRepeat(char[] cs,char c){
		int l=cs.length;
		for(int i=l-1;i>=0;i--){
			if(cs[i]!=c){
				return Arrays.copyOfRange(cs,0,i+1);
			}
		}
		return cs;
	}
	
	/** 
	 * removeStartEnd
	 * @param cs
	 * @param c
	 * @return
	 */
	public static char[] removeStartEndRepeat(char[] cs,char c){
		return removeEndRepeat(removeStartRepeat(cs, c),c);
	}
	
	public static void main(String[] args) {
		char[] cs=new char[]{'*','*','*','*','1','2','3','4','*','*','*','*'};
		System.out.println(removeStartEndRepeat(cs, '*'));
		
	}
}
